/*
 * ProjetChatView.java
 */

package client;

import Common.Message;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import org.jdesktop.application.Action;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;

/**
 * The application's main frame.
 */
public class ProjetChatView extends FrameView {

    /**
     * This method is the constructor of the ProjetChatView class.
     * @param app the ancestor of this FrameView
     */
    public ProjetChatView(SingleFrameApplication app) {
        super(app);

        initComponents();
        jTabbedPane1.removeAll();
        jTextArea1.setAutoscrolls(true);
        jTextArea2.setAutoscrolls(true);
        setFrameEnabled(false);
        disconnectMenuItem.setEnabled(false);
        sendMenuItem.setEnabled(false);
		jProgressBar1.setVisible(false);
    }

 

    /**
     * This method displays the about box.
     */
    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = ProjetChatApp.getApplication().getMainFrame();
            aboutBox = new ProjetChatAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        ProjetChatApp.getApplication().show(aboutBox);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        connectMenuItem = new javax.swing.JMenuItem();
        disconnectMenuItem = new javax.swing.JMenuItem();
        sendMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        statusMessageLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        statusLabel = new javax.swing.JLabel();
        jProgressBar1 = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        jSplitPane1.setName("jSplitPane1"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jList1.setName("jList1"); // NOI18N
        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        jSplitPane1.setLeftComponent(jScrollPane1);

        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
        jTabbedPane1.setName("jTabbedPane1"); // NOI18N

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane2.setViewportView(jTextArea1);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(client.ProjetChatApp.class).getContext().getResourceMap(ProjetChatView.class);
        jTabbedPane1.addTab(resourceMap.getString("jScrollPane2.TabConstraints.tabTitle"), jScrollPane2); // NOI18N

        jSplitPane1.setRightComponent(jTabbedPane1);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        connectMenuItem.setText(resourceMap.getString("connectMenuItem.text")); // NOI18N
        connectMenuItem.setName("connectMenuItem"); // NOI18N
        connectMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(connectMenuItem);

        disconnectMenuItem.setText(resourceMap.getString("disconnectMenuItem.text")); // NOI18N
        disconnectMenuItem.setName("disconnectMenuItem"); // NOI18N
        disconnectMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                disconnectMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(disconnectMenuItem);

        sendMenuItem.setText(resourceMap.getString("sendMenuItem.text")); // NOI18N
        sendMenuItem.setName("sendMenuItem"); // NOI18N
        sendMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(sendMenuItem);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(client.ProjetChatApp.class).getContext().getActionMap(ProjetChatView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        jButton1.setText(resourceMap.getString("buttonSend.text")); // NOI18N
        jButton1.setName("buttonSend"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSendActionPerformed(evt);
            }
        });

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jTextArea2.setName("jTextArea2"); // NOI18N
        jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                Send(evt);
            }
        });
        jScrollPane3.setViewportView(jTextArea2);

        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        statusLabel.setText(resourceMap.getString("statusLabel.text")); // NOI18N
        statusLabel.setName("statusLabel"); // NOI18N

        jProgressBar1.setOrientation(1);
        jProgressBar1.setName("jProgressBar1"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusMessageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 386, Short.MAX_VALUE))
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 307, Short.MAX_VALUE)
                        .addGap(31, 31, 31)
                        .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))))
                .addGap(33, 33, 33))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE)
                    .addGroup(statusPanelLayout.createSequentialGroup()
                        .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(statusPanelLayout.createSequentialGroup()
                                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(statusPanelLayout.createSequentialGroup()
                                        .addComponent(statusMessageLabel)
                                        .addGap(14, 14, 14))
                                    .addComponent(jButton2)))
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(statusLabel))))
                .addContainerGap())
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void Send(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_Send
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {            
            String t = ""+'\n';
            if (jTextArea2.getText().equalsIgnoreCase(t))
                jButton2.doClick();
            else if (!jTextArea2.getText().isEmpty())
                jButton1.doClick();
        }
        else if (!evt.isActionKey() && !evt.isAltDown() && !evt.isControlDown() && !evt.isMetaDown() && !evt.isShiftDown()){
            String t = ""+'\n';
            if (jTextArea2.getText().equalsIgnoreCase(t))
                jTextArea2.replaceRange("", 0, 1);
        }
    }//GEN-LAST:event_Send

    private void buttonSendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSendActionPerformed
        String t = ""+'\n';
        if (!jTextArea2.getText().equalsIgnoreCase(t) && !jTextArea2.getText().isEmpty()) {
            if (jTabbedPane1.getSelectedIndex() != 0) {
                    int index = jTabbedPane1.getSelectedIndex();
                    int num=0;
                    for(int i = 0; i < jList1.getModel().getSize(); i++) {
                        if (jList1.getModel().getElementAt(i).toString().equalsIgnoreCase(jTabbedPane1.getTitleAt(index))) {
                            num = i;
                            break;
                        }
                    }
                    if (!jtexts[num].getText().isEmpty()) {
                        jtexts[num].append("\n");
                        jtexts[num].append(nick + " : ");
                        jtexts[num].append(jTextArea2.getText());
                        Message msg = new Message(Message.PRIVATE_MESSAGE, nick, jList1.getModel().getElementAt(num).toString(), jTextArea2.getText());
                        cli.sendMessage(msg);
                        jTextArea2.setText("");
                    }
                    else {
                        jtexts[num].append(nick + " : ");
                        jtexts[num].append(jTextArea2.getText());
                        Message msg = new Message(Message.PRIVATE_MESSAGE, nick, jList1.getModel().getElementAt(num).toString(), jTextArea2.getText());
                        cli.sendMessage(msg);
                        jTextArea2.setText("");
                    }
                }
            else {
                if (!jtexts[0].getText().isEmpty()) {
                    jtexts[0].append("\n");
                    jtexts[0].append(nick + " : ");
                    jtexts[0].append(jTextArea2.getText());
                    Message msg = new Message(Message.PUBLIC_MESSAGE, nick, "none", jTextArea2.getText());
                    cli.sendMessage(msg);
                    jTextArea2.setText("");
                }
                else {
                    jtexts[0].append(nick + " : ");
                    jtexts[0].append(jTextArea2.getText());
                    Message msg = new Message(Message.PUBLIC_MESSAGE, nick, "none", jTextArea2.getText());
                    cli.sendMessage(msg);
                    jTextArea2.setText("");
                }
            }
        }
        jButton2.doClick();
}//GEN-LAST:event_buttonSendActionPerformed

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked

        if (evt.getClickCount() == 2 && evt.getButton() == evt.BUTTON1) {
            int index = jList1.locationToIndex(evt.getPoint());
            String titre = jList1.getModel().getElementAt(index).toString();
            boolean verif = false;
            for (int i = 0; i < jTabbedPane1.getTabCount(); i++) {
                if (jTabbedPane1.getTitleAt(i).equalsIgnoreCase(titre))
                    verif = true;
                if (verif) {
                    jTabbedPane1.setSelectedIndex(i);
                    break;
                }
            }
            if (verif == false) {
                jtexts[index] = new javax.swing.JTextArea();
                jtexts[index].setColumns(20);
                jtexts[index].setEditable(false);
                jtexts[index].setRows(5);
                jtexts[index].setAutoscrolls(true);
                int nb = this.getScrollsLenght();
                jscrolls[nb] = new JScrollPane(jtexts[index]);
                jTabbedPane1.addTab(titre, jscrolls[nb]);
                jTabbedPane1.setSelectedIndex(jTabbedPane1.getTabCount()-1);
                jtexts[index].addMouseListener(new MouseListener() {

                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == 3) {
                            final JPopupMenu closeMenu = new JPopupMenu();
                            JMenuItem closeItem = new JMenuItem("Close this tab");
                            closeMenu.add(closeItem);
                            closeMenu.show(jTabbedPane1.getSelectedComponent(), e.getX(), e.getY());
                            closeItem.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    int i = jTabbedPane1.getSelectedIndex();
                                    jTabbedPane1.remove(i);
                                    closeMenu.setVisible(false);
                                }
                            });
                        }
                    }

                    public void mousePressed(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseReleased(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseEntered(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseExited(MouseEvent e) {
                        //nothing to do
                    }
                });
            }
        }
        else if (evt.getButton() == evt.BUTTON3) {
            final MouseEvent mEvt = evt;
            final int index = jList1.locationToIndex(mEvt.getPoint());
            if (index != -1 && index != 0) {
                final JPopupMenu labelPopupMenu = new JPopupMenu();
                JMenuItem sendF = new JMenuItem("Send file ...");
                JMenuItem kick = new JMenuItem("Kick him !");
                labelPopupMenu.setLocation(mEvt.getPoint());
                labelPopupMenu.add(sendF);
                labelPopupMenu.add(kick);
                labelPopupMenu.show(jList1, mEvt.getX(), mEvt.getY());
                sendF.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        sendMenuItemActionPerformed(e);
                        labelPopupMenu.setVisible(false);
                    }
                });
                kick.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        String dest = jList1.getModel().getElementAt(index).toString();
                        Message msg = new Message(Message.KICK_MESSAGE, nick, dest , nick + " wants to kick " + dest + ".");
                        cli.sendMessage(msg);
                        labelPopupMenu.setVisible(false);
                    }
                });
                mainPanel.addMouseListener(new MouseListener() {

                    public void mouseClicked(MouseEvent e) {
                        labelPopupMenu.setVisible(false);
                    }

                    public void mousePressed(MouseEvent e) {
                        labelPopupMenu.setVisible(false);
                    }

                    public void mouseReleased(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseEntered(MouseEvent e) {
                       //nothing to do
                    }

                    public void mouseExited(MouseEvent e) {
                        //nothing to do
                    }
                });
                statusPanel.addMouseListener(new MouseListener() {

                    public void mouseClicked(MouseEvent e) {
                        labelPopupMenu.setVisible(false);
                    }

                    public void mousePressed(MouseEvent e) {
                        labelPopupMenu.setVisible(false);
                    }

                    public void mouseReleased(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseEntered(MouseEvent e) {
                       //nothing to do
                    }

                    public void mouseExited(MouseEvent e) {
                        //nothing to do
                    }
                });
                
            }
        }
    }//GEN-LAST:event_jList1MouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        jTextArea2.setText("");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void connectMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectMenuItemActionPerformed
        String[] args = {};
        ConnectView.main(args, this);

    }//GEN-LAST:event_connectMenuItemActionPerformed

    private void disconnectMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_disconnectMenuItemActionPerformed
        connectMenuItem.setEnabled(true);
        disconnectMenuItem.setEnabled(false);
        sendMenuItem.setEnabled(false);
        jTabbedPane1.setTitleAt(0, "Not Connected");
        DefaultListModel list = new DefaultListModel();
        jList1.setModel(list);
		jList1.removeAll();
        cli.disconnect(true);
        setFrameEnabled(false);
        JOptionPane.showMessageDialog(mainPanel, "You've been disconnected from server.","Disconnected", JOptionPane.INFORMATION_MESSAGE);
        connected = false;
        setStatus("Not Connected.");
}//GEN-LAST:event_disconnectMenuItemActionPerformed

    private void sendMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendMenuItemActionPerformed

        setSendEnabled(false);
        String[] args = {};
        SendView s = new SendView(this, cli);
        s.setLocationRelativeTo(null);
        s.main(args, this, cli);
}//GEN-LAST:event_sendMenuItemActionPerformed

    /**
     * This method display a personnal message sent by one client in the tab corresponding to this client (if this tab is not opened yet, it open the tab) and put it in front of other tabs.
     * @param message the message to display.
     */
    public void displayPersonnalMessage(Message message) {
        int index_nickname = -1;
        for(int i = 0; i < jList1.getModel().getSize(); i++) {
            if (jList1.getModel().getElementAt(i).toString().equalsIgnoreCase(message.getNickSrc())) {
                index_nickname = i;
                break;
            }
        }
        String titre = jList1.getModel().getElementAt(index_nickname).toString();
        boolean verif = false;
        for (int i = 0; i < jTabbedPane1.getTabCount(); i++) {
            if (jTabbedPane1.getTitleAt(i).equalsIgnoreCase(titre))
                verif = true;
            if (verif) {
                jTabbedPane1.setSelectedIndex(i);
                break;
            }
        }
        if (index_nickname != -1) {
            if (verif) {
                if (jtexts[index_nickname].getText().isEmpty()) {
                    jtexts[index_nickname].append(message.getNickSrc() + " : ");
                    jtexts[index_nickname].append(message.getMessage());
                }
                else {
                    jtexts[index_nickname].append('\n' + message.getNickSrc() + " : ");
                    jtexts[index_nickname].append(message.getMessage());
                }
            }
            else {
                jtexts[index_nickname] = new javax.swing.JTextArea();
                jtexts[index_nickname].setColumns(20);
                jtexts[index_nickname].setEditable(false);
                jtexts[index_nickname].setRows(5);
                jtexts[index_nickname].setAutoscrolls(true);
                int nb = this.getScrollsLenght();
                jscrolls[nb] = new JScrollPane(jtexts[index_nickname]);
                jTabbedPane1.addTab(titre, jscrolls[nb]);
                jTabbedPane1.setSelectedIndex(jTabbedPane1.getTabCount()-1);
                jtexts[index_nickname].append(message.getNickSrc() + " : ");
                jtexts[index_nickname].append(message.getMessage());
                jtexts[index_nickname].addMouseListener(new MouseListener() {

                    public void mouseClicked(MouseEvent e) {
                        if (e.getButton() == 3) {
                            final JPopupMenu closeMenu = new JPopupMenu();
                            JMenuItem closeItem = new JMenuItem("Close this tab");
                            closeMenu.add(closeItem);
                            closeMenu.show(jTabbedPane1.getSelectedComponent(), e.getX(), e.getY());
                            closeItem.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    int i = jTabbedPane1.getSelectedIndex();
                                    jTabbedPane1.remove(i);
                                    closeMenu.setVisible(false);
                                }
                            });
                        }
                    }

                    public void mousePressed(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseReleased(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseEntered(MouseEvent e) {
                        //nothing to do
                    }

                    public void mouseExited(MouseEvent e) {
                        //nothing to do
                    }
                });
            }
        }
    }

    /**
     * This method displays a message sent by one client on the public channel.
     * @param message the message to display.
     */
    public void displayPublicMessage(Message message) {
        if (jtexts[0].getText().isEmpty()) {
              jtexts[0].append(message.getNickSrc() + " : ");
              jtexts[0].append(message.getMessage());
        }
        else {
              jtexts[0].append('\n' + message.getNickSrc() + " : ");
              jtexts[0].append(message.getMessage());
        }
    }

    /**
     * This method add a client from the jList on the left.
     * @param nick the nickname of the new client.
     */
    public void addClientToList(String nick) {
        DefaultListModel list = new DefaultListModel();
        for (int i =0; i < jList1.getModel().getSize(); i++) {
            list.addElement(jList1.getModel().getElementAt(i));
        }
        list.addElement(nick);
        jList1.setModel(list);
		if(jList1.getModel().getSize() == 1) {
			jTabbedPane1.add(nick, jScrollPane2);
		}
    }

    /**
     * This method set the main frame disabled, and displays a message dialog to say the user he has been disconnected.
     */
    public void disconnection() {
        setFrameEnabled(false);
        connectMenuItem.setEnabled(true);
        disconnectMenuItem.setEnabled(false);
		sendMenuItem.setEnabled(false);
        deleteClientFromList(jTabbedPane1.getTitleAt(0).toString());
        userMessage("Disconnected", "You've been disconnected from server.");
        connected = false;
        setStatus("Not Connected.");
    }

    /**
     * This method displays a Message Dialog to the user.
     * @param title the title of the message dialog to display.
     * @param msg the message of the message dialog to display.
     */
    public void userMessage(String title, String msg) {
        JOptionPane.showMessageDialog(mainPanel, msg,title, JOptionPane.INFORMATION_MESSAGE);
    }

    /**
     * This method delete a client from the jList on the left.
     * @param nick the nickname to delete from the list.
     */
    public void deleteClientFromList(String nick) {
        int index_nickname = -1;
        boolean opentab = false;
        int index = -1;
        for (int i = 0; i < jTabbedPane1.getTabCount(); i++) {
            if (jTabbedPane1.getTitleAt(i).equalsIgnoreCase(nick)) {
                opentab = true;
                index = i;
                break;
            }
        }
        if (opentab) {
            jTabbedPane1.remove(index);
        }
        for(int i = 0; i < jList1.getModel().getSize(); i++) {
            if (jList1.getModel().getElementAt(i).toString().equalsIgnoreCase(nick)) {
                index_nickname = i;
                break;
            }
        }
        if (index_nickname != -1) {
            DefaultListModel liste = new DefaultListModel();
            for (int k = 0; k < jList1.getModel().getSize(); k++) {
                if (!jList1.getModel().getElementAt(k).toString().equalsIgnoreCase(nick)) {
                    liste.addElement(jList1.getModel().getElementAt(k));
                }
            }
            jList1.setModel(liste);
            for (int j =0; j < (this.getTextsLenght()-1); j++) {
                if (j >= index_nickname) {
                    jtexts[j] = jtexts[index_nickname+1];
                }
            }
        }

    }

    /**
     * This method set the ClientNetwork attribute.
     * @param client the new ClientNetwork.
     */
    public void setClient(ClientNetwork client) {
        cli = client;
    }

    /**
     * This method set the objects of the main frame enabled or disabled.
     * @param b if true, all the objects are set enabled.
     */
    public void setFrameEnabled(boolean b) {
        jButton1.setEnabled(b);
        jButton2.setEnabled(b);
        jList1.setEnabled(b);
        jTextArea1.setEnabled(b);
        jTextArea2.setEditable(b);
        jTextArea2.setEnabled(b);
		try {
			for (int i =0; i < this.getTextsLenght(); i++) {
				jtexts[i].setEnabled(b);
			}
		}
		catch (Exception e) {
			//do nothing
		}
    }

    /**
     * This method set the connected attribute with the boolean parameter b.
     * @param b
     */
    public void setConnected(boolean b) {
        connected = b;
    }

    /**
     * This method return true if the client is connected to a server.
     * @return if client is connected or not.
     */
    public boolean isConnected() {
        return connected;
    }

    /**
     * This method set the client's nickname.
     * @param n the new nickname.
     */
    public void setNick(String n) {
        nick = n;
    }

    /**
     * This method purpose to the user to accept or deny a file transfert proposition by a message dialog.
     * @param message the FILE_PROPOSE message received.
     */
    public void messagePropose(Message message) {
        int response = JOptionPane.showConfirmDialog(mainPanel, message.getNickSrc() + " want to send you " + message.getMessage() + ", do you accept it ?", "File Transfert", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION) {
            try {
                File f = new File(System.getProperty("user.home") + "/" + message.getMessage());
                boolean b = f.createNewFile();
                if (b) {
                    this.setProgressBarInderterminate(true);
                    this.setProgressBarVisible(true);
                    Message msg = new Message(Message.FILE_ACCEPT, nick, message.getNickSrc(), "none");
                    cli.sendMessage(msg);
                    ClientThread client = cli.getClientThread();
                    client.fileTransfertInit(f, message.getNickSrc());
                    setStatus("Reception du fichier " + f.getName() + "...");
                }
                else{
                    userMessage("Error", "This file already exists, the file cannot be received.");
                    Message msg = new Message(Message.FILE_DENY, nick, message.getNickSrc(), "none");
                    cli.sendMessage(msg);
                }
            } catch (IOException ex) {
                userMessage("Error", "An I/O error has occurred, the file couldn't be created.");
                Message msg = new Message(Message.FILE_DENY, nick, message.getNickSrc(), "none");
                cli.sendMessage(msg);
            }
        }
        else {
            Message msg = new Message(Message.FILE_DENY, nick, message.getNickSrc(), "none");
            cli.sendMessage(msg);
        }
    }

    /**
     * This method inform the user that the file transfert were refused by the recipient.
     * @param nickDest nickname of the recipient.
     */
    public void fileToSendDenied(String nickDest) {
        JOptionPane.showMessageDialog(mainPanel, nickDest + " refused file transfert.", "File transfert aborted", JOptionPane.WARNING_MESSAGE);
    }

    /**
     * This method is a getter for the list of clients connected to the same server.
     * @return jList of clients.
     */
    public JList getList() {
        return jList1;
    }

    /**
     * This method is a getter for status attribute.
     * @return string displayed as status.
     */
    public String getStatus() {
        return statusLabel.getText();
    }

    /**
     * This method set the status label (at the bottom of the main frame).
     * @param s string to display as status.
     */
    public void setStatus(String s) {
        statusLabel.setText(s);
    }

    /**
     * This method is a getter for nick attribute.
     * @return nickname of client.
     */
    public String getNick() {
        return nick;
    }

    /**
     * This method set the property enabled of the connect menu item in File menu.
     * @param b if true, connectMenuItem is set enabled.
     */
    public void setConnectEnabled(boolean b){
        connectMenuItem.setEnabled(b);
    }

    /**
     * This method set the property enabled of the disconnect menu item in File menu.
     * @param b if true, disconnectMenuItem is set enabled.
     */
    public void setDisconnectEnabled(boolean b){
        disconnectMenuItem.setEnabled(b);
    }

    /**
     * This method set the property enabled of the send menu item in File menu.
     * @param b if true, sendMenuItem is set enabled.
     */
    public void setSendEnabled(boolean b) {
        sendMenuItem.setEnabled(b);
    }


    /**
     * This method animate the progress bar.
     * @param b if true, the progress bar moves.
     */
    public void setProgressBarInderterminate(boolean b){
		jProgressBar1.setIndeterminate(b);
	}

    /**
     * This method set the visibility of the progress bar.
     * @param b if true, the progress bar become visible.
     */
    public void setProgressBarVisible(boolean b) {
		jProgressBar1.setVisible(b);
	}

    /**
     * This method remove all the opened tabs.
     */
    public void resetTabs() {
        jtexts = null;
		jtexts = new javax.swing.JTextArea[50];
		jtexts[0] = jTextArea1;
        jscrolls = null;
        jscrolls = new JScrollPane[50];
        jscrolls[0] = jScrollPane2;
		jTabbedPane1.removeAll();
	}

    private int getScrollsLenght() {
        int nb = 0;
        for (int i = 0; i < 50; i++) {
            if (jscrolls[i] != null)
                nb++;
            else
                break;
        }
        return nb;
    }

    private int getTextsLenght() {
        int nb = 0;
        for (int i = 0; i < 50; i++) {
            if (jscrolls[i] != null)
                nb++;
            else
                break;
        }
        return nb;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem connectMenuItem;
    private javax.swing.JMenuItem disconnectMenuItem;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem sendMenuItem;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables



    private javax.swing.JTextArea[] jtexts = new javax.swing.JTextArea[50];
    private JScrollPane[] jscrolls = new JScrollPane[50];
    private ClientNetwork cli;
    private JDialog aboutBox;
    private String nick;
    private boolean connected;

}
